package crawler.asidunmading;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.zql.entity.AgencyEntity;

import util.Location;
import util.MybatisTool;
import util.ProCity;

public class ASiDunMaDing {
	List<AgencyEntity> getAgency() {
		List<AgencyEntity> list = new ArrayList<AgencyEntity>();
		String getDealer = "http://www2.astonmartin.com/zh/%E7%BB%8F%E9%94%80%E5%95%86";
		try {
			Document doc = Jsoup.connect(getDealer).get();
			Elements dealerCols = doc.getElementsByClass("sf_cols");
			for (Element ele1 : dealerCols) {
				Elements dealers = ele1.getElementsByClass("sfContentBlock");
				for (Element ele2 : dealers) {
					if (ele2.children().size() < 3) {
						continue;
					}
					String name = ele2.getElementsByTag("h2").get(0).text();
					String address = ele2.getElementsByTag("p").get(0).text();
					String sellTell = "";
					String n=ele2.getElementsByTag("p").toString();
					if(n.contains("+86")) {
					sellTell = ele2.getElementsByTag("p").get(2).text();
					if(sellTell.contains("：")) {
						sellTell = sellTell.split("：")[1];
					}else {}
					}else {
						sellTell ="";
					}
					String[] lngAndLat = Location.getLocation(address);
					String[] proCity = ProCity.getData(lngAndLat);
					String lng = lngAndLat[0];
					String lat = lngAndLat[1];
					String proName = proCity[0];
					String cityName = proCity[1];

					AgencyEntity agency = new AgencyEntity();
					agency.setdCloseDate(null);
					agency.setdOpeningDate(null);
					agency.setdUpdateTime(new Timestamp(System.currentTimeMillis()));
					agency.setnBrandID(-1);
					agency.setsBrand("阿斯顿马丁");
					agency.setnDealerIDWeb(-1);
					agency.setnManufacturerID(-1);
					agency.setsManufacturer("阿斯顿马丁");
					agency.setnState(1);
					agency.setsAddress(address);
					agency.setsCity(cityName);
					agency.setsCustomerServiceCall(null);
					agency.setsDealerName(name);
					agency.setsDealerType(null);
					agency.setsProvince(proName);
					agency.setsSaleCall(sellTell);

					agency.setsLongitude(lng);
					agency.setsLatitude(lat);
					//System.out.println(agency);
					list.add(agency);

				}

			}

		} catch (IOException e) {

			e.printStackTrace();
		}

		return list;
	}
	public static void main(String[] args) {
		ASiDunMaDing crawler = new ASiDunMaDing();
		System.out.println("爬虫开始...");
		List<AgencyEntity> agencys = crawler.getAgency();
		System.out.println("抓取完毕,正在存库");
		for (AgencyEntity agency : agencys) {
			MybatisTool.save(agency);
		}
		MybatisTool.close();
		System.out.println("请查看数据库");
	}
}
